/*******************************************************************************
 * Copyright (c) 2011 Irineu Martins de Lima Moura (imlm2).
 * This file is part of JBeat.
 * 
 *     JBeat is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU Lesser General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 * 
 *     JBeat is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU Lesser General Public License for more details.
 * 
 *     You should have received a copy of the GNU Lesser General Public License
 *     along with JBeat.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * Contributors:
 *     Irineu Martins de Lima Moura (imlm2) - initial API and implementation
 ******************************************************************************/
package br.ufpe.cin.imlm2.jbeat.soot.throwableset.generation;

import java.util.Collection;
import java.util.List;

import soot.Body;
import soot.SootClass;
import soot.SootMethod;
import soot.Unit;
import soot.jimple.toolkits.annotation.arraycheck.ArrayBoundsChecker;
import soot.jimple.toolkits.annotation.nullcheck.NullPointerChecker;
import soot.util.Chain;
import br.ufpe.cin.imlm2.jbeat.soot.throwableset.InstructionInspector;
import br.ufpe.cin.imlm2.jbeat.soot.throwableset.InstructionVisitor;
import br.ufpe.cin.imlm2.jbeat.soot.throwableset.tags.ThrowableSetTag;

public class GeneratesCalculator extends InstructionInspector {

	public GeneratesCalculator(List<String> excludeClasses,
			List<String> excludePackages, boolean rtLibraries) {
		super(excludeClasses, excludePackages, rtLibraries);
	}

	@Override
	protected void checkTags(SootMethod m) {
		if(!m.hasTag(ThrowableSetTag.TAG_NAME)){
			m.addTag(new ThrowableSetTag());
		}
	}
	
	@Override
	protected void executePreTaggingTransformations(Collection<SootClass> classes) {
		for (SootClass sootClass : classes) {
			List<SootMethod> methods = sootClass.getMethods();
			this.filterOutMethods(methods);
			for (SootMethod sootMethod : methods) {
				Body b = sootMethod.retrieveActiveBody();
				ArrayBoundsChecker abc = ArrayBoundsChecker.v();
				abc.transform(b);
				NullPointerChecker npc = NullPointerChecker.v();
				npc.transform(b);			
			}
		}
	}

	@Override
	protected void visitInstructions(SootMethod sootMethod) {
		Body b = sootMethod.retrieveActiveBody();
		Chain<Unit> stmts = b.getUnits();
		InstructionVisitor gv = new GeneratesVisitor(b);	
		for (Unit unit : stmts) {
			unit.apply(gv);
		}
		ThrowableSetTag tst = (ThrowableSetTag) sootMethod.getTag(ThrowableSetTag.TAG_NAME);
		tst.addAllExceptions(gv.getExceptions());

	}	

}
